<template>
  <q-virtual-scroll
    :items="tabs"
    virtual-scroll-horizontal
    v-slot="{ index, item }"
  >
    <div :key="index" class="row items-center" style="height: 62px">
      <q-separator v-if="index === 0" vertical spaced />
      <q-btn
        :key="index"
        flat
        color="primary"
        :label="item.name"
        icon="api"
        @click="onClick(item.id)"
      />
      <q-icon clickable name="delete" @click="onDelete(item.id)"></q-icon>
      <q-separator vertical spaced />
    </div>
    <p></p>
  </q-virtual-scroll>
</template>

<script setup>
import { ref, onUnmounted, onMounted } from "vue";
import { emitter } from "../boot/global_variable";
const tabs = ref([]);

const onClick = (id) => {
  console.log("[api_changed:emit]=>", id);
  emitter.emit("api_changed", id);
};

const onDelete = (id) => {
  let index = 0;
  for (var i = 0; i < tabs.value.length; i++) {
    if (tabs.value[i].id === id) {
      tabs.value.splice(i, 1);
      index = i;
      break;
    }
  }

  // 激活临近的标签,先左边标签优先
  let newid = "";
  console.log(tabs.value.length, index);
  if (tabs.value.length > 0) {
    if (tabs.value.length == 1) {
      newid = tabs.value[0].id;
    } else {
      newid = tabs.value[index - 1].id;
    }
  }

  console.log("[api_changed:emit]=>", newid);
  emitter.emit("api_changed", newid);
};

onMounted(() => {
  // 订阅节点
  emitter.on("node_changed", (param) => {
    console.log("[node_changed:on]=>", param);

    const tab = {
      id: param.id,
      name: param.name,
    };

    // 检查是否存在
    let exist = false;
    for (let ele of tabs.value) {
      if (ele.id === tab.id) {
        exist = true;
        break;
      }
    }

    if (!exist) {
      tabs.value.push(tab);
    }

    console.log("[api_changed:emit]=>", tab.id);
    emitter.emit("api_changed", tab.id);
  });

  emitter.on("node_deleted", (id) => {
    console.log("[node_deleted:on]=>", id);
    for (let i = 0; i < tabs.value.length; i++) {
      const ele = tabs.value[i];
      if (ele.id == id) {
        tabs.value.splice(i, 1);
      }
    }
  });
});

onUnmounted(() => {
  emitter.off("node_changed");
  console.log("[emitter:off]=>node_changed");
  emitter.off("node_deleted");
  console.log("[emitter:off]=>node_deleted");
});
</script>
